package com.sihai.ehr.web.action.train;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.TrainCategory;
import com.sihai.ehr.model.biz.TrainLecturer;
import com.sihai.ehr.model.biz.TrainMaterResource;
import com.sihai.ehr.model.biz.TrainPlan;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.TrainCategoryService;
import com.sihai.ehr.service.TrainLecturerService;
import com.sihai.ehr.service.TrainMaterResourceService;
import com.sihai.ehr.service.TrainPlanService;
import com.sihai.ehr.web.action.EHRAction;

/**
 * 培训类型控制器
 * 
 * @author henry
 * 
 */
@Results({ @Result(name = "main", location = "materresource_main.jsp"), 
		@Result(name = "list", location = "res_mater_list.jsp"),
		@Result(name = "res_realia_list", location = "res_realia_list.jsp"), 
		@Result(name = "materresource_manage_main", location = "materresource_manage_main.jsp"),
		@Result(name = "materresource_list", location = "materresource_list.jsp"), 
		@Result(name = "plan_print_main", location = "plan_print_main.jsp"),
		@Result(name = "plan_print_list", location = "plan_print_list.jsp") })
public class TrainMaterResourceAction extends EHRAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Log log = LogFactory.getLog(TrainMaterResourceAction.class);

	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private TrainPlanService trainPlanService;
	@BeanInject
	private TrainCategoryService trainCategoryService;
	@BeanInject
	private TrainLecturerService trainLecturerService;
	@BeanInject
	private TrainMaterResourceService trainMaterResourceService;

	private List<Organization> organizations;
	private List<TrainCategory> categories;
	private List<TrainLecturer> lecturers;
	private LimitedList<TrainPlan> plans;
	private LimitedList<TrainMaterResource> resources;
	private TrainPlan plan;
	private Long planId;
	private String ids;
	private List<String> searchyears;
	// 搜索
	private int year;
	private int lecturerType;
	private String category;
	private Long workId;

	@Action("/train/materresource_main")
	@Override
	public String execute() throws Exception {
		listTitle = "教材资源管理";
		listAction = "/train/res_mater_list.xhtml";
		organizations = organizationService.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;

		Calendar mCalendar = Calendar.getInstance();
		if (searchyears == null) {
			searchyears = new ArrayList<String>();
		}
		searchyears.add(String.valueOf(mCalendar.get(Calendar.YEAR)));
		searchyears.add(String.valueOf(mCalendar.get(Calendar.YEAR) - 1));
		searchyears.add(String.valueOf(mCalendar.get(Calendar.YEAR) - 2));
		searchyears.add(String.valueOf(mCalendar.get(Calendar.YEAR) - 3));

		categories = trainCategoryService.getTrainCategories(organizationId, null, null);
		lecturers = trainLecturerService.getTrainLecturers(organizationId, -1L, null, null);
		return "main";
	}

	@Action("/train/res_mater_list")
	public String list() {
		listAction = "/train/res_mater_list.xhtml";
		plans = trainPlanService.getTrainPlans(year, lecturerType, category, workId, createLimit(), createSorter());
		paging(plans);
		/* 设置翻页action */
		this.setPageUrl("train/res_mater_list.xhtml");
		return "list";
	}

	@Action("/train/res_realia_list")
	public String dispatchRealiaList() {
		listAction = "/train/res_realia_list.xhtml";
		plans = trainPlanService.getTrainPlans(year, lecturerType, category, workId, createLimit(), createSorter());
		paging(plans);
		/* 设置翻页action */
		this.setPageUrl("train/res_realia_list.xhtml");
		return "res_realia_list";
	}

	/**
	 * 教育资源管理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/materresource_manage_main")
	public String executeMater() throws Exception {
		listTitle = "教材资源管理 - 上传";
		listAction = "/train/materresource_list.xhtml";
		if (planId != null || planId > 0) {
			plan = trainPlanService.getTrainPlan(planId);
		}
		return "materresource_manage_main";
	}

	/**
	 * 教育资源列表
	 * 
	 * @return
	 */
	@Action("/train/materresource_list")
	public String dispatchMaterList() {
		listAction = "/train/materresource_list.xhtml";
		if (planId != null || planId > 0) {
			// plan = trainPlanService.getTrainPlan(planId);
			resources = trainMaterResourceService.getTrainMaterResourcesByPlanId(planId, createLimit(), createSorter());
		}
		this.paging(resources);
		/* 设置翻页action */
		this.setPageUrl("train/materresource_list.xhtml");
		return "materresource_list";
	}

	@Action(value = "/train/materresource_delete", results = { @Result(name = "success", type = "plainText") })
	public String deleteMaterresource() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				// 删除文件
				for (String s : ids.split(",")) {
					TrainMaterResource materResource = trainMaterResourceService.getTrainMaterResource(Long.parseLong(s));
					File f = new File(ServletActionContext.getRequest().getRealPath(materResource.getCoursewareUrl()));
					if (f.exists()) {
						f.delete();
					}
				}
				// 删除数据库
				trainMaterResourceService.deleteTrainMaterResource(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}
		}

		return SUCCESS;
	}

	// 计划教育资源打印
	/**
	 * 教育资源管理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/plan_print_main")
	public String executeMaterPrint() throws Exception {
		listTitle = "员工培训计划 - 打印";
		listAction = "/train/plan_print_list.xhtml";
		if (planId != null || planId > 0) {
			plan = trainPlanService.getTrainPlan(planId);
		}
		return "plan_print_main";
	}

	/**
	 * 教育资源列表
	 * 
	 * @return
	 */
	@Action("/train/plan_print_list")
	public String dispatchMaterPrintList() {
		listAction = "/train/plan_print_list.xhtml";
		if (planId != null || planId > 0) {
			plan = trainPlanService.getTrainPlan(planId);
			resources = trainMaterResourceService.getTrainMaterResourcesByPlanId(planId, createLimit(), createSorter());
		}
		this.paging(resources);
		/* 设置翻页action */
		this.setPageUrl("train/plan_print_list.xhtml");
		return "plan_print_list";
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public List<TrainCategory> getCategories() {
		return categories;
	}

	public void setCategories(List<TrainCategory> categories) {
		this.categories = categories;
	}

	public List<TrainLecturer> getLecturers() {
		return lecturers;
	}

	public void setLecturers(List<TrainLecturer> lecturers) {
		this.lecturers = lecturers;
	}

	public LimitedList<TrainPlan> getPlans() {
		return plans;
	}

	public void setPlans(LimitedList<TrainPlan> plans) {
		this.plans = plans;
	}

	public LimitedList<TrainMaterResource> getResources() {
		return resources;
	}

	public void setResources(LimitedList<TrainMaterResource> resources) {
		this.resources = resources;
	}

	public TrainPlan getPlan() {
		return plan;
	}

	public void setPlan(TrainPlan plan) {
		this.plan = plan;
	}

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public List<String> getSearchyears() {
		return searchyears;
	}

	public void setSearchyears(List<String> searchyears) {
		this.searchyears = searchyears;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getLecturerType() {
		return lecturerType;
	}

	public void setLecturerType(int lecturerType) {
		this.lecturerType = lecturerType;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public Long getWorkId() {
		return workId;
	}

	public void setWorkId(Long workId) {
		this.workId = workId;
	}
}
